package com.example.last.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.last.common.Result;
import com.example.last.common.enums.ErrorCode;
import com.example.last.entity.Type;
import com.example.last.entity.Params;
import com.example.last.exception.CustomException;
import com.example.last.service.TypeService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RequestMapping("/type")
@RestController
public class TypeController {
    @Resource
   private TypeService typeService;
    @GetMapping("/findAll")
    public Result findAll(){
        List<Type> list = typeService.findAll();
        return Result.success(list);
    }
    
    @GetMapping("/search")
    public Result findBySearch(@Param("params") Params params){
        PageInfo<Type> info = typeService.findBySearch(params);
        return Result.success(info);
    }
    //新增图书信息
    @PostMapping
    public Result save(@RequestBody Type type){
        if(type.getId() == null){
            typeService.add(type);
        }else{
            typeService.update(type);
        }
        return Result.success();
    }
    //删除图书信息
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        typeService.delete(id);
        return Result.success();
    }

    //批量删除
    @PutMapping("/batch")
    public Result batchdel(@RequestBody List<Type> list){
        for(Type type : list){
            typeService.delete(type.getId());
        }
        return Result.success();
    }

    //导出excel和下载
    @GetMapping("/export")
    public Result export(HttpServletResponse response) throws IOException {
        //1.从数据库查询所有数据
        List<Type> all = typeService.findAll();
        if(CollectionUtil.isEmpty(all)){
            throw new CustomException(ErrorCode.PARAM_CHECK_ERROR);
        }
        //2.定义一个list，处理后的数据塞到list里
        List<Map<String,Object>> list = new ArrayList<>(all.size());
        //定义Map<key,value>出来，遍历数据封装到Mao<key,value>里
        for(Type type : all){
            Map<String,Object> row = new HashMap<>();
            row.put("类别名称",type.getType_name());
            row.put("类别描述",type.getDescription());

            list.add(row);
        }
        //4.创建一个ExcelWriter，把list数据生成出来
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list,true);
        //5.下载excel
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=type.xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        writer.close();
        IoUtil.close(System.out);


        return Result.success();
    }
    //上传文件数据
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        System.out.println("-------------------");
        List<Type> infoList = ExcelUtil.getReader(file.getInputStream()).readAll(Type.class);
        if (!CollectionUtils.isEmpty(infoList)) {
            for (Type type : infoList) {
                try {
                    typeService.add(type);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.success();
    }

}
